#include "game.h"
#include "scene_main.h"
#include "SDL_image.h"

Game::Game()
{
}

Game::~Game()
{
    clean();
}

void Game::init()
{
    /// SDL初始化
    if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
    {
        SDL_LogError( SDL_LOG_CATEGORY_ERROR, "Couldn't initialize SDL: %s", SDL_GetError() );
        is_running_ = false;
        exit(1);
    }


    /// 创建窗口
    pwindow_ = SDL_CreateWindow("SDL2", SDL_WINDOWPOS_UNDEFINED, 
                                SDL_WINDOWPOS_UNDEFINED, 
                                window_width_, 
                                window_height_,
                                SDL_WINDOW_SHOWN);

    if (pwindow_ == nullptr)
    {
        SDL_LogError( SDL_LOG_CATEGORY_ERROR, "Couldn't create window: %s", SDL_GetError() );
        is_running_ = false;
        exit(1);
    }

    /// 创建渲染器
    prenderer_ = SDL_CreateRenderer(pwindow_, -1, SDL_RENDERER_ACCELERATED);
    if (prenderer_ == nullptr)
    {
        SDL_LogError( SDL_LOG_CATEGORY_ERROR, "Couldn't create renderer: %s", SDL_GetError() );
        is_running_ = false;
        exit(1);
    }

    if(IMG_Init(IMG_INIT_PNG) != IMG_INIT_PNG)
    {
        SDL_LogError( SDL_LOG_CATEGORY_ERROR, "Couldn't initialize SDL_image: %s", SDL_GetError() );
        is_running_ = false;
        exit(1);
    }



    /// 创建主场景
    pcurrent_scene_ = new SceneMain();
    pcurrent_scene_->init();

}

void Game::clean()
{
    if (pcurrent_scene_ != nullptr) 
    {
        pcurrent_scene_->clean();
        delete pcurrent_scene_;
    }
    
    SDL_DestroyRenderer(prenderer_);
    SDL_DestroyWindow(pwindow_);
    IMG_Quit();
    SDL_Quit();
}

void Game::run()
{
    /// 游戏主循环
    while (is_running_)
    {
        auto frameStart = SDL_GetTicks();
        /// 获得事件
        SDL_Event event;
        SDL_zero(event);
        handleEvent(event);
        update(deltaTime_);
        render();
        auto frameEnd = SDL_GetTicks();
        auto diff = frameEnd - frameStart;
        if (diff < frameTime_)   
        {
            SDL_Delay(frameTime_ - diff);
            deltaTime_ = frameTime_ / 1000.0f;
        }
        else
        {
            deltaTime_ = diff / 1000.0f;
        }
    }
}

void Game::changeScene(Scene *pscene)
{
    if (pcurrent_scene_ != nullptr)
    {
        pcurrent_scene_->clean();
        delete pcurrent_scene_;
    }
    
    pcurrent_scene_ = pscene;   
}

void Game::handleEvent(SDL_Event event)
{
    while (SDL_PollEvent(&event))
    {

        if (event.type == SDL_QUIT)
        {
            is_running_ = false;
            break;
        }
        pcurrent_scene_->handleEvent(event);   
    }
}

void Game::update(float deltaTime)
{
    pcurrent_scene_->update(deltaTime);
}

void Game::render()
{
    /**
     * 清除缓存区 
     * 绘制内容到缓存区
     * 显示缓存区
     */
    SDL_RenderClear(prenderer_);    
    pcurrent_scene_->render();
    SDL_RenderPresent(prenderer_);
}
